#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>

#define MAXDATASIZE 100

int tcp_client(char *hostname, int port) {
    int sockfd, sendbytes;
    struct hostent* host;
    struct sockaddr_in serv_addr;


    host = gethostbyname(hostname); //转换为hostent
	
	// 1. 创建 client socket （基于 TCP 传输）
    if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
        perror("创建 client socket 失败");
        exit(1);
    }
	
	// 2. 设置服务端连接地址 (IPv4 + PORT)
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    serv_addr.sin_addr = *((struct in_addr *)host->h_addr);
	
	// 3. 连接服务端 
    if((connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))) == -1) {
        perror("connect error");
        exit(1);
    }
	

	return sockfd;
}
